import json

from django.http import JsonResponse

# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.exceptions import NotFound

from book.models import BookInfo
from .serializers_2 import BookSerializer


class BooksView(APIView):

    def post(self, request):
        # 接收
        data = json.loads(request.body.decode())
        book = BookSerializer(data=data)

        # 验证
        book.is_valid(raise_exception=True)

        # 处理
        book.save()

        # 响应
        return Response(book.validated_data)

    def get(self, request):
        books = BookInfo.objects.all()
        books = BookSerializer(books, many=True)
        return Response(books.data)


class BookView(APIView):

    def get(self, request, pk):
        try:
            book = BookInfo.objects.get(id=pk)
        except:
            raise NotFound('图书没找到')

        book = BookSerializer(book)

        return Response(book.data)

    def delete(self, request, pk):
        BookInfo.objects.filter(id=pk).delete()
        return Response()

    def put(self, request, pk):
        # 接收
        data = json.loads(request.body.decode())

        # 验证
        try:
            book = BookInfo.objects.get(id=pk)
        except:
            raise NotFound('图书没找到')

        book = BookSerializer(book, data)
        book.is_valid(raise_exception=True)

        # 处理
        book.save()

        # 相应
        return Response(book.validated_data)


